package com.renchunlin.banner

import android.content.Context
import android.database.DataSetObserver
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.renchunlin.banner.utils.SizeUtils


/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/5/14.
 * PS: Not easy to write code, please indicate.
 */
class BannerView : LinearLayout {

    private lateinit var mViewPager: ViewPager
    private lateinit var content_title: TextView
    private lateinit var content_point_container: LinearLayout
    private lateinit var mTitleBindListener: TitleBindListener
    private lateinit var mInnerAdapter: InnerPageAdapter

    constructor(context: Context?) : this(context, null)

    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        LayoutInflater.from(context).inflate(R.layout.banner_view, this, true)
        initView()
        initEvent()
    }

    private fun initView() {
        mViewPager = this.findViewById(R.id.mViewPager)
        //设置页面之间的边距。    相邻页面之间的距离（以像素为单位）
        mViewPager.pageMargin = SizeUtils.dip2px(context, 20f)
        mViewPager.offscreenPageLimit = 3
        content_title = this.findViewById(R.id.content_title)
        content_point_container = this.findViewById(R.id.content_point_container)

    }

    private fun initEvent() {
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {

            /**
             *
             * @param position position有两个情况，position positionOffset 为0时，就是当前的Position
             *                 如果有滑动，position则会是下一个准备看到的position
             *
             * @param positionOffset 位置偏移量，取值为0到1，[0，1）
             * @param positionOffsetPixels 位置偏移量，这个是像素界别的
             */
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                //滑动时的回调
            }

            override fun onPageSelected(position: Int) {
                //滑动以后停下来的回调，position指所停在的位置
                //这个时候我们去获取标题
                val title = mTitleBindListener.getTitle(position)
                content_title.text = title
            }


            override fun onPageScrollStateChanged(state: Int) {
                //滑动状态的改变，有停止的，滑动中的.
                //ViewPager#SCROLL_STATE_IDLE
                //ViewPager#SCROLL_STATE_DRAGGING
                //ViewPager#SCROLL_STATE_SETTLING
            }

        })
    }

    interface TitleBindListener {
        fun getTitle(position: Int): String
    }

    public fun setData(innerPageAdapter: InnerPageAdapter, titleBindListener: TitleBindListener) {
        mViewPager.adapter = innerPageAdapter
        mViewPager.currentItem = Int.MAX_VALUE / 2 + 1
        this.mInnerAdapter = innerPageAdapter
        this.mTitleBindListener = titleBindListener
        val title = mTitleBindListener.getTitle(0)
        content_title.text = title
        //创建圆点
        updateIndicator()
        innerPageAdapter.registerDataSetObserver(object : DataSetObserver(){
            override fun onChanged() {
                updateIndicator()
            }
        })
    }

    abstract inner class InnerPageAdapter : PagerAdapter() {

        abstract val getDateSize: Int

        override fun getCount(): Int {
            //因为要无限轮播嘛，所以我们就给一个IntegerMaxValue
            return Int.MAX_VALUE
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view == `object`
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            //载入view，至于显示什么view,不用管，由外面给进来。只要对position进行一个转换
            val itemPosition = position % getDateSize
            val itemView = getItemView(container, itemPosition)
            container.addView(itemView)
            return itemView
        }

        protected abstract fun getItemView(container: ViewGroup, itemPosition: Int): View

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }
    }

    //动态添加圆点
    fun updateIndicator() {
        //先删除
        content_point_container.removeAllViews()
        val indicatorSize = mInnerAdapter.getDateSize
        for (i in 0 until indicatorSize) {
            val view = View(context)
            if (mViewPager.currentItem % indicatorSize == 1) {
                view.setBackgroundColor(Color.parseColor("#ff0000"))
            } else {
                view.setBackgroundColor(Color.parseColor("#ffffff"))
            }
            val layoutParams = LayoutParams(
                SizeUtils.dip2px(context, 5f), SizeUtils.dip2px(context, 5f)
            )
            layoutParams.setMargins(
                SizeUtils.dip2px(context, 5f),
                0,
                SizeUtils.dip2px(context, 5f),
                0
            )
            view.layoutParams = layoutParams
            content_point_container.addView(view)
        }
    }
}